<?php
/**
 * 银行，地区相关
 * User: John
 * Date: 16-12-29
 * Time: 下午5:04
 */
namespace app\backend\model;

use think\Model;

class Business extends Model
{
    private $subbranchTable = 'z_bank_subbranch';
    private $bankCodeTable = 'z_bank_code';
    private $bankAreaTable = 'z_bank_area';
    private $areaTable     = 'z_area';
    public function __construct() {
        parent::__construct();
    }

    /**
     * 获取省份
     * @date   2016-1-9
     * @author Lanlc
     *
     *
     * @return
     */
    public function getArea($id)
    {
        if (is_array($id)) {//省份信息
            $where = [
                'area_id' => ['IN', $id]
            ];
        } else {//某个省的城市信息或某市的区县信息
            $where = [
                'area_parent_id' => $id
            ];
        }

        $res = $this->table($this->areaTable)->where($where)->field('area_id as code, area_name as name, area_parent_id')->select();
        return $res;
    }

    /**
     * 获取银行信息
     * @author lanlc
     * @date   2016-07-08
     *
     * @param  $cityId 城市代码 1620 => 大同市
     * @param  $bankId 银行代码 504 => 恒生银行
     * @param  $searchName 模糊搜索 词
     * @param  $page 第几页
     * @param  $size 条数
     * @return
     */
    public function getSubbranch($cityId, $bankId, $searchName = '', $page = 1, $size = 500)
    {
        $cityId     = intval($cityId);
        $bankId     = intval($bankId);
        $searchName = strval($searchName);
        $page       = intval($page);
        $size       = intval($size);

        if (!$cityId || !$bankId) {
            return false;
        }

        $where = [
            'city'    => $cityId,
            'bank_id' => $bankId
        ];

        if ($searchName !== '') {
            $where['name'] = ['like', "%{$searchName}%"];
        }
        $offSet = ($page-1)*$size;

        $field = 'code,name,phone';

        $count   = $this->setTable($this->subbranchTable)->field($field)->where($where)->count();
        $list    = $this->setTable($this->subbranchTable)->field($field)->where($where)->limit($offSet, $size)->select();

        return $list === false ? false : ['count' => $count, 'list' => $list];
    }

    /**
     * 获取银行代码
     * @date   2016-01-10
     * @author Lanlc
     *
     *
     * @return
     */
    public function bankCode()
    {
        return $this->setTable($this->bankCodeTable)->select();
    }

    /**
     * 获取省份
     * @date   2016-01-10
     * @author Lanlc
     *
     * @return
     */
    public function getBankProvince()
    {
        return $this->setTable($this->bankAreaTable)->where(['parent_id' => 0])->select();
    }

    /**
     * 获取市
     * @date   2016-01-10
     * @author Lanlc
     *
     * @return
     */
    public function getBankArea($provinceId)
    {
        return $this->setTable($this->bankAreaTable)->where(['parent_id' => $provinceId])->select();
    }
}
